package com.wuh.controller;

import com.github.pagehelper.PageInfo;
import com.wuh.model.Teacher;
import com.wuh.model.User;
import com.wuh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(User user, HttpSession session){
        User u  =userService.login(user);
        if (u !=null){
            session.setAttribute("sess_user",u);
            session.setAttribute("loginMessage","user");
            String a = u.getLogin_name();
            session.setAttribute("loginname", a);
            return "redirect:/";
        }else{
                session.setAttribute("msg","用户名或密码错误");
                return  "redirect:/toLogin";
        }
    }

    @RequestMapping("/register")
    public  String register(User user, Model model){
        Integer i = userService.register(user);
            if(i>0){
                model.addAttribute("n",user.getLogin_name());
                return "loginreg/login";
            }else {
                return "redirect：/toRegister";
            }
    }

    @PostMapping("/edituUerInfo")
    public  String edituUerInfo(User user,String bitrhy,String birthm,HttpSession session) throws ParseException {
        DateFormat dateFormat =new SimpleDateFormat("yyyy-MM");
        String s =bitrhy+"-"+birthm;
        Date date = dateFormat.parse(s);
        user.setBirthday(date);
        User user1 = (User) session.getAttribute("sess_user");
        User user2 = userService.selectUserByName(user1.getLogin_name());
        user.setUser_id(user2.getUser_id());
        userService.editUserInfo(user);
        session.setAttribute("sess_user", user);
        return "redirect:/toUserInfo";
    }

    @RequestMapping("/editUserPassword")
	@ResponseBody   //ajax注解
	public int editUserPassword(String oldPassword,String newPassword,HttpSession session) {
		int flag = 0;
		User user = (User) session.getAttribute("sess_user");
		if(oldPassword.equals(user.getPassword())) {
			user.setPassword(newPassword);
			flag = userService.editPasswordById(user);

		}

		return flag;
	}

//    @RequestMapping("/toUserUpload")
//	public String toUserUpload() {
//		return  "person/test";
//	}

    @RequestMapping("/userUpload")
    public String userUpload(MultipartFile upImage,HttpSession session) {

    	User user = new User();
    	User sess_user = (User) session.getAttribute("sess_user");
    	user.setUser_id(sess_user.getUser_id());
        System.out.println("修改接收到的user：" + user);
        if (!upImage.isEmpty()) {
            //获取项目文件地址
        	String filepath = new String("src/main/resources/"+"static/user/img");
        	File staticFile = new File(filepath);
            //设置文件名
        	String fileName = upImage.getOriginalFilename();  //获取原文件名
            String uuid = UUID.randomUUID().toString().replace("-", ""); //把文件的名称设置唯一值，uuid
            fileName = uuid + "_" + fileName; //文件名
            //图片保存全路径
            String uploadPath = staticFile.getAbsolutePath() + File.separator + fileName;
            File targetFile = new File(uploadPath);
            //上传文件

            if (!targetFile.exists()) {
            	targetFile.mkdirs();
            	System.out.println("创建新文件");
            }
            try {
                upImage.transferTo(targetFile);  //上传
                System.out.println("上传成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //存储图片访问地址
            fileName = "/user\\img\\" + fileName;
            user.setImg_url(fileName);
            userService.editUserInfo(user);
            //更新session
            sess_user  =userService.getUserById(sess_user.getUser_id());
            session.setAttribute("sess_user",sess_user);
        }
        return "redirect:/toUserInfo";
    }

    @RequestMapping("/getUsers")
	public String getUsers(User user,Model model) {
    	user.setPageSize(5);
    	PageInfo<User> pageInfo = userService.getUsers(user);
		model.addAttribute("pageInfo",pageInfo);
		model.addAttribute("schUser",user);

		return "person/user_List";
	}

    @GetMapping("/delUsers")
	public String delUsers(Integer[] ids) {
    	userService.delUsers(ids);

		return "redirect:/getUsers";
	}

    @GetMapping("/freezeUsers")
	public String freezeUsers(Integer[] ids) {
    	userService.freezeUsers(ids);

    	return "redirect:/getUsers";
	}

    @GetMapping("/unfreezeUsers")
	public String unfreezeUsers(Integer[] ids) {
    	userService.unfreezeUsers(ids);

    	return "redirect:/getUsers";
	}

}
